package com.wnxy.e_reentrant;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

// 死锁演示：多个线程互相持有对方的锁
public class DeadLock {

    private static ReentrantLock lockA = new ReentrantLock();
    private static ReentrantLock lockB = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            try {
                // 尝试获取A锁，如果1秒后还没有获取，就返回false
                if (lockA.tryLock(1, TimeUnit.SECONDS)) {
                    System.out.println("AAAAA");

                    if (lockB.tryLock(1,TimeUnit.SECONDS)) {
                        System.out.println("BBBBB");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lockA.isLocked()) {
                    lockA.unlock();
                }
                if (lockB.isLocked()) {
                    lockB.unlock();
                }

            }

        },"t1");

        Thread t2 = new Thread(()->{
            try {
                // 尝试获取A锁，如果1秒后还没有获取，就返回false
                if (lockB.tryLock(1, TimeUnit.SECONDS)) {
                    System.out.println("CCCCC");

                    if (lockA.tryLock(1,TimeUnit.SECONDS)) {
                        System.out.println("DDDDD");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lockB.isLocked()) {
                    lockB.unlock();
                }
                if (lockA.isLocked()) {
                    lockA.unlock();
                }

            }
        },"t2");

        t1.start();
        t2.start();
    }
}
